/************************************************************************************************/
/* Author:         Gerald St-Georges                                                            */
/* Date:           November 9, 2015                                                             */
/* Description:    Initial Database and Table creation                                          */
/*                                                                                              */
/* Important Note: This script will be used for initial installation of Database                */
/*                 VoxcoEnvironmentConfigand and any futur upodates.                            */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                    */
/*                 with "if NOT EXISTS..." script before the new update since the entire script */
/*                 will be run every time the manager is executed.                              */
/************************************************************************************************/
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT Name FROM master.dbo.sysdatabases WHERE Name = 'VoxcoEnvironment')
BEGIN
 CREATE DATABASE VoxcoEnvironment
END
GO

USE VoxcoEnvironment
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Role_Template]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Role_Template] 
 ( 
  [Id] integer Identity NOT NULL,
  [ModuleName] nvarchar(150) NOT NULL, 
  [Version] nvarchar(50) NULL, 
  [VersionDateTime] nvarchar(255) NULL, 
  [AssemblyName] nvarchar(255) NULL, 
  [AssemblyType] nvarchar(255) NULL, 
  [ApplicationFamily] nvarchar(30) NULL, 
  [Obsolete] bit NOT NULL DEFAULT 0, 
  [ZipFileNameList] nvarchar(max) NULL,
  Constraint [pk_Role_Template] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Servers]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Servers] 
 ( 
  [Id] integer Identity NOT NULL,
  [ServerGuid] uniqueidentifier, 
  [ServerAddress] nvarchar(150) NOT NULL, 
  [Req] nvarchar(30) NULL, 
  [ForceInstall] bit NOT NULL DEFAULT 0, 
  [ForceUninstall] bit NOT NULL DEFAULT 0, 
  [InstallState] nvarchar(30) NULL, 
  Constraint [pk_Servers] Primary Key ([Id]) 
 ) 
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Server_Roles]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Server_Roles] 
 ( 
  [Id] integer Identity NOT NULL,
  [ServerId] int NOT NULL, 
  [RoleTemplateId] int NOT NULL, 
  [Selected] bit NOT NULL DEFAULT 0, 
  [ConfigDate] datetime NULL, 
  [ConfigVersion] nvarchar(50) NULL, 
  [InstallDate] datetime NULL, 
  [InstallVersion] nvarchar(50) NULL, 
  [InstallState] nvarchar(30) NULL, 
  Constraint [pk_Server_Roles] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Config]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Config] 
 ( 
  [Id] integer Identity NOT NULL,
  [ServerGuid] uniqueidentifier, 
  [Product] nvarchar(255) NULL, 
  [ConfigKey] nvarchar(255) NOT NULL, 
  [ConfigValue] nvarchar(max) NULL, 
  Constraint [pk_Install_Config] Primary Key ([Id]) 
 )
 ALTER TABLE [VoxcoEnvironment].[dbo].[Install_Config]
 ADD CONSTRAINT uc_ConfigID UNIQUE ([ServerGuid],[Product],[ConfigKey])
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Data_Audit]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Data_Audit] 
 ( 
  [Id] integer Identity NOT NULL,
  [UserName] nvarchar(255) NOT NULL,
  [ComputerName] nvarchar(255) NOT NULL,
  [Action] nvarchar(255) NOT NULL,
  [Table] nvarchar(255) NOT NULL,
  [RecordId] int NOT NULL,
  [Field] nvarchar(255),
  [OldValue] nvarchar(MAX) NOT NULL,
  [NewValue] nvarchar(MAX) NOT NULL,
  [ModifiedDate] DATETIME NOT NULL, 
  Constraint [pk_Install_Data_Audit] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Package]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Package] 
 ( 
  [Id] integer identity NOT NULL,
  [Version] nvarchar(50) NOT NULL,
  [InstallType] nvarchar(50) NOT NULL,
  [InstallAction] nvarchar(50) NOT NULL,
  [HealthState] nvarchar(255) NULL,
  [ProgressState] nvarchar(255) NULL,
  [UninstallPackageId] integer NULL,
  [UserName] nvarchar(255) NOT NULL,
  [Computer] nvarchar(255) NOT NULL,
  [Date] DATETIME NOT NULL, 
  [LastModifiedDate] DATETIME NULL, 
  Constraint [pk_Install_Package] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Package_Patch]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Package_Patch] 
 ( 
  [Id] integer identity NOT NULL,
  [PackageId] integer NOT NULL,
  [InstallSequence] integer NOT NULL,
  [PatchNumber] integer NULL,
  [HealthState] nvarchar(255) NULL,
  [ProgressState] nvarchar(255) NULL,
  [UserName] nvarchar(255) NOT NULL,
  [Computer] nvarchar(255) NOT NULL,
  [Date] DATETIME NOT NULL, 
  [LastModifiedDate] DATETIME NULL, 
  Constraint [pk_Install_Package_Patch] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Package_Server]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Package_Server] 
 ( 
  [Id] integer identity NOT NULL,
  [PackageId] integer NOT NULL,
  [ServerGuid] uniqueidentifier,
  [ServerAddress] nvarchar(150) NOT NULL,
  [HealthState] nvarchar(255) NULL,
  [ProgressState] nvarchar(255) NULL,
  [UserName] nvarchar(255) NOT NULL,
  [Computer] nvarchar(255) NOT NULL,
  [Date] DATETIME NOT NULL, 
  [LastModifiedDate] DATETIME NULL, 
  Constraint [pk_Install_Package_Server] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Package_Server_Activity]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Package_Server_Activity] 
 ( 
  [Id] integer identity NOT NULL,
  [PackageId] integer NOT NULL,
  [PackagePatchId] integer NOT NULL,
  [InstallSequence] integer NOT NULL,
  [PatchNumber] integer NULL,
  [HealthState] nvarchar(255) NULL,
  [ProgressState] nvarchar(255) NULL,
  [ServerGuid] uniqueidentifier,
  [ServerAddress] nvarchar(150) NOT NULL,
  [UserName] nvarchar(255) NOT NULL,
  [Computer] nvarchar(255) NOT NULL,
  [Date] DATETIME NOT NULL, 
  [LastModifiedDate] DATETIME NULL, 
  Constraint [pk_Install_Package_Server_Activity] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Install_Log]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Install_Log] 
 ( 
  [InstallId] integer NOT NULL,
  [ServerGuid] uniqueidentifier,
  [ServerAddress] nvarchar(150) NOT NULL,
  [ModuleName] nvarchar(150) NOT NULL,
  [VerboseSequence] int NOT NULL,
  [Message] nvarchar(MAX) NOT NULL,
  [ExceptionMessage] nvarchar(MAX) NULL,
  [StackTrace] nvarchar(MAX) NULL,
  [ProcessState] nvarchar(255) NOT NULL,
  [HealthState] nvarchar(255) NOT NULL,
  [IsPublic] bit NOT NULL,
  [ModifiedDate] DATETIME NOT NULL, 
  Constraint [pk_Install_Log] Primary Key ([InstallId],[ServerGuid],[VerboseSequence]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Patch]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Patch] 
 ( 
  [Id] integer identity NOT NULL,
  [Version] nvarchar(50) NOT NULL,
  [PatchNumber] int NOT NULL, 
  [PatchName] nvarchar(50) NOT NULL,
  [PatchDate] datetime NOT NULL, 
  [InstallId] integer NULL,
  [InstallDate] datetime NULL, 
  [InstallState] nvarchar(30) NULL, 
  Constraint [pk_Patch] Primary Key ([Id]) 
 )
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Server_Role_Patch] 
 ( 
  [Id] integer identity NOT NULL,
  [Version] nvarchar(50) NOT NULL, 
  [PatchNumber] int NOT NULL, 
  [ServerId] int NOT NULL, 
  [ModuleName] nvarchar(150) NOT NULL,
  [ModuleVersion] nvarchar(50) NOT NULL,
  [ServerRoleId] int NOT NULL,
  [ServerGuid] uniqueidentifier,
  [ServerAddress] nvarchar(150) NOT NULL,
  [InstallId] int NULL,
  [InstallDate] datetime NULL, 
  [InstallState] nvarchar(30) NULL, 
  [SupersededByPatch] nvarchar(10) NULL, 
  Constraint [pk_Server_Role_Patch] Primary Key ([Id]) 
 )
END
GO

IF NOT EXISTS (SELECT * FROM [VoxcoEnvironment].[dbo].[Install_Config] WHERE ConfigKey = 'ConfigLockPwd')
BEGIN
  INSERT INTO [VoxcoEnvironment].[dbo].[Install_Config] (ServerGuid, Product, ConfigKey, ConfigValue) 
    VALUES(cast(cast(0 as binary) as uniqueidentifier), null,'ConfigLockPwd', '') 
END
GO

IF NOT EXISTS (SELECT * FROM [VoxcoEnvironment].[dbo].[Install_Config] WHERE ConfigKey = 'EnvironmentId')
BEGIN
  INSERT INTO [VoxcoEnvironment].[dbo].[Install_Config] (ServerGuid, Product, ConfigKey, ConfigValue) 
    VALUES(cast(cast(0 as binary) as uniqueidentifier), null,'EnvironmentId',CONVERT(varchar(MAX), NEWID())) 
END
GO

/*************************************************************************************************/
/* Author:         Gerald St-Georges                                                             */
/* Date:           July 24, 2017                                                                 */
/* Description:    Changes to VoxcoEnvironment Database must be done using update scripts bellow */
/*                 this note with test enabling script to be run multiple times without risking  */
/*                 double running of update scripts.                                             */
/*                                                                                               */
/* Important Note: This script will be used for initial installation of Database                 */
/*                 VoxcoEnvironmentConfigand and any futur upodates.                             */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                     */
/*                 with "if NOT EXISTS..." script before the new update since the entire script  */
/*                 will be run every time the manager is executed.                               */
/*************************************************************************************************/
GO

IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]') AND type in (N'U'))
BEGIN
	IF NOT EXISTS(SELECT 1 FROM sys.columns   WHERE Name = N'BackupFileName'   AND Object_ID = Object_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]'))
	BEGIN
		--Create the New column
		ALTER TABLE  [VoxcoEnvironment].[dbo].[Server_Role_Patch] ADD BackupFileName nvarchar(max) not null default ''
	END
END
GO

IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'Server_Role_Patch'
                  AND Column_name = 'SupersededByPatch' AND Character_Maximum_Length = 10)
BEGIN
	ALTER TABLE [Server_Role_Patch] ALTER Column [SupersededByPatch] nvarchar(50) NULL
END
GO

IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]') AND type in (N'U'))
BEGIN
	IF NOT EXISTS(SELECT 1 FROM sys.columns   WHERE Name = N'UninstallState'   AND Object_ID = Object_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]'))
	BEGIN
		--Create the New column
		ALTER TABLE  [VoxcoEnvironment].[dbo].[Server_Role_Patch] ADD UninstallState nvarchar(30) not null default ''
	END
	IF NOT EXISTS(SELECT 1 FROM sys.columns   WHERE Name = N'UninstallDate'   AND Object_ID = Object_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]'))
	BEGIN
		--Create the New column
		ALTER TABLE  [VoxcoEnvironment].[dbo].[Server_Role_Patch] ADD UninstallDate datetime NULL
	END
END
GO

IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]') AND type in (N'U'))
BEGIN
	IF EXISTS(SELECT 1 FROM sys.columns   WHERE Name = N'BackupFileName'   AND Object_ID = Object_ID(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch]'))
	BEGIN

		--Drop constaint for column BackupFileName
		DECLARE @sql NVARCHAR(MAX)
		WHILE 1=1
		BEGIN
			SELECT TOP 1 @sql = N'alter table Server_Role_Patch drop constraint ['+dc.NAME+N']'
			from sys.default_constraints dc
			JOIN sys.columns c
				ON c.default_object_id = dc.object_id
			WHERE 
				dc.parent_object_id = OBJECT_ID('Server_Role_Patch')
			AND c.name = N'BackupFileName'
			IF @@ROWCOUNT = 0 BREAK
			EXEC (@sql)
		END		

		--Drop Column BackupFileName
		ALTER TABLE  [VoxcoEnvironment].[dbo].[Server_Role_Patch] DROP COLUMN [BackupFileName];
	END
END
GO

IF (object_id(N'[VoxcoEnvironment].[dbo].[Server_Role_Patch_ZipFile]', 'U') is null)
BEGIN
 Create table [VoxcoEnvironment].[dbo].[Server_Role_Patch_ZipFile] 
 ( 
  [Id] integer identity NOT NULL,
  [ServerRolePatchId] int NOT NULL, 
  [ServerId] int NOT NULL, 
  [ServerRoleId] int NOT NULL, 
  [ModuleName] nvarchar(150) NOT NULL,
  [ZipFileName] nvarchar(150) NOT NULL,
  [BackupFileName] nvarchar(300) NOT NULL,
  Constraint [pk_Server_Role_Patch_ZipFile] Primary Key ([Id]) 
 )
END
GO

/*************************************************************************************************/
/* Author:         Pascal Roy                                                                    */
/* Date:           January 29, 2019                                                              */
/* Description:    Changed the Install_log table to add a specific ID Primary Key field.         */
/*                                                                                               */
/*                                                                                               */
/*                                                                                               */
/* Important Note: This script will be used for initial installation of Database                 */
/*                 VoxcoEnvironmentConfigand and any futur upodates.                             */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                     */
/*                 with "if NOT EXISTS..." script before the new update since the entire script  */
/*                 will be run every time the manager is executed.                               */
/*************************************************************************************************/
IF NOT EXISTS( SELECT 1 FROM sys.columns 
               WHERE Name = N'LogId' AND
                     Object_ID = Object_ID(N'Install_Log') )
BEGIN
	ALTER TABLE [VoxcoEnvironment].[dbo].[Install_Log]
	DROP CONSTRAINT pk_Install_Log;   

    ALTER TABLE [VoxcoEnvironment].[dbo].[Install_Log]
	ADD LogId BigInt IDENTITY(1,1)
	
	ALTER TABLE [VoxcoEnvironment].[dbo].[Install_Log]
    ADD CONSTRAINT pk_Install_Log PRIMARY KEY(LogId)
END
GO

/*************************************************************************************************/
/* Author:         Gerald St-Georges                                                             */
/* Date:           July 25, 2019                                                                 */
/* Description:    Changed  the Install_Data_Audit table to add an audit group ID field.         */
/*                                                                                               */
/*                                                                                               */
/*                                                                                               */
/* Important Note: This script will be used for initial installation of Database                 */
/*                 VoxcoEnvironmentConfigand and any futur updates.                              */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                     */
/*                 with "if NOT EXISTS..." script before the new update since the entire script  */
/*                 will be run every time the manager is executed.                               */
/*************************************************************************************************/
IF NOT EXISTS( SELECT 1 FROM sys.columns 
               WHERE Name = N'AuditGroupNumber' AND
                     Object_ID = Object_ID(N'Install_Data_Audit') )
BEGIN
    ALTER TABLE [VoxcoEnvironment].[dbo].[Install_Data_Audit] ADD AuditGroupNumber BigInt
END
GO

/*************************************************************************************************/
/* Author:         Gerald St-Georges                                                             */
/* Date:           July 29, 2019                                                                 */
/* Description:    Changed  the Servers table to add an ServiceUpgrading field.                  */
/*                 Byte containing 0 when the install service is not being apgraded.             */
/*                                                                                               */
/*                                                                                               */
/* Important Note: This script will be used for initial installation of Database                 */
/*                 VoxcoEnvironmentConfigand and any futur updates.                              */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                     */
/*                 with "if NOT EXISTS..." script before the new update since the entire script  */
/*                 will be run every time the manager is executed.                               */
/*************************************************************************************************/
IF NOT EXISTS( SELECT 1 FROM sys.columns 
               WHERE Name = N'IsServiceUpgrading' AND
                     Object_ID = Object_ID(N'Servers') )
BEGIN
    ALTER TABLE [VoxcoEnvironment].[dbo].[Servers] ADD IsServiceUpgrading bit NOT NULL Default 0
    ALTER TABLE [VoxcoEnvironment].[dbo].[Servers] ADD ServiceUpgradeStartDate datetime NULL
END
GO


/****************************************************************************************************/
/* Author:         Gerald St-Georges                                                                */
/* Date:           Septembre 13, 2019                                                               */
/* Description:    Changed colums OldValue and NewValue of table Install_Data_Audit to allow Nulls  */
/*                                                                                                  */
/* Important Note: This script will be used for initial installation of Database                    */
/*                 VoxcoEnvironmentConfigand and any futur updates.                                 */
/*                 DO NOT MODIFY EXISTING SCRIPT, only add new update script                        */
/*                 with "if NOT EXISTS..." script before the new update since the entire script     */
/*                 will be run every time the manager is executed.                                  */
/****************************************************************************************************/
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = object_id('dbo.Install_Data_Audit') 
                    AND [name] = 'OldValue' AND is_nullable = 1)
BEGIN
  ALTER TABLE Install_Data_Audit ALTER COLUMN [OldValue] NVARCHAR(MAX) NULL;
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = object_id('dbo.Install_Data_Audit') 
                    AND [name] = 'NewValue' AND is_nullable = 1)
BEGIN
  ALTER TABLE Install_Data_Audit ALTER COLUMN [NewValue] NVARCHAR(MAX) NULL;
END
GO
